#include "customdroptableview.h"
#include <QDragEnterEvent>
#include "customdropeventsubwnd.h"
#include <QMimeData>
#include <QStandardItemModel>
#include <QDebug>

CustomDropTableView::CustomDropTableView(QWidget *parent):QTableView (parent)
{
    this->setAcceptDrops(true);
}

CustomDropTableView::~CustomDropTableView()
{

}

void CustomDropTableView::dragEnterEvent(QDragEnterEvent *event)
{
    if(this->model()==nullptr||this->model()->columnCount()!=0)
    {
        event->ignore();
        return;
    }
    event->accept();
}

void CustomDropTableView::dropEvent(QDropEvent *event)
{
    QString _format=QString("application/x-qabstractitemmodeldatalist");
    QByteArray encoded = event->mimeData()->data(_format);
    QDataStream stream(&encoded, QIODevice::ReadOnly);

    QVector<QMap<int, QVariant> > data;
    while (!stream.atEnd()) {
        int r, c;
        QMap<int, QVariant> v;
        stream >> r >> c >> v;
        data.append(v);
    }
    if(data.size()>0)
    {
        if(data[0].contains(0))
        {
            QString _str=(data[0][0]).toString();
            addColumn(_str);
            CustomDropEventSubWnd* _subWnd=qobject_cast<CustomDropEventSubWnd*>(event->source());
            if(_subWnd)
             _subWnd->removeSelectItem();
        }
    }
}

void CustomDropTableView::addColumn(const QString &title)
{
    if(this->model()==nullptr)return;
    QStandardItemModel* _model=qobject_cast<QStandardItemModel*>(this->model());
    QStandardItem* _item=new QStandardItem();
    _item->setTextAlignment(Qt::AlignCenter);
    _item->setText(title);
    _item->setTextAlignment(Qt::AlignCenter);
    _model->setHorizontalHeaderItem(0,_item);
}

void CustomDropTableView::mousePressEvent(QMouseEvent *event)
{
    event->ignore();
}
